package com.projectzqjz.parttimework.ui.activity;

import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.projectzqjz.parttimework.App;
import com.projectzqjz.parttimework.R;
import com.projectzqjz.parttimework.adapter.PartApplyAdapter;
import com.projectzqjz.parttimework.adapter.PartSearchAdapter;
import com.projectzqjz.parttimework.base.BaseActivity;
import com.projectzqjz.parttimework.customprovider.GridItemDecoration;
import com.projectzqjz.parttimework.entity.DailyEntity;
import com.projectzqjz.parttimework.entity.PartBaseEntity;
import com.projectzqjz.parttimework.entity.ScreenEntity;
import com.projectzqjz.parttimework.net.MyCallback;
import com.projectzqjz.parttimework.net.NoValidationTask;
import com.projectzqjz.parttimework.utils.NewsToastUtils;
import com.projectzqjz.parttimework.utils.ScreenUtil;
import com.projectzqjz.putorefresh.BaseBothListener;
import com.projectzqjz.putorefresh.PullToBothLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

public class PartSearchActivity extends BaseActivity {
    @BindView(R.id.view_status_bar_place)
    View statusBarPlace;
    @BindView(R.id.recycle_1)
    RecyclerView recycle_1;
    @BindView(R.id.recycle_2)
    RecyclerView recycle_2;
    @BindView(R.id.ll_rm)
    LinearLayout ll_rm;
    @BindView(R.id.pullRefresh)
    PullToBothLayout pullToBothLayout;
    @BindView(R.id.edit_search)
    EditText edit_search;
    @BindView(R.id.search_noData)
    ImageView search_noData;
    private PartApplyAdapter dailyAdapter = null;
    private List<DailyEntity> list = new ArrayList<>();
    List<ScreenEntity> sexList = new ArrayList<>();
    private PartSearchAdapter screenSexAdapter = null;
    private int page = 1;
    private boolean isRefresh = true;
    private String search = null;

    @Override
    public void setListen() {
        edit_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (edit_search.getText().toString().length() == 0) {
                    pullToBothLayout.setVisibility(View.GONE);
                    ll_rm.setVisibility(View.VISIBLE);
                    search_noData.setVisibility(View.GONE);
                }else {
                    edit_search.setSelection(edit_search.getText().length());
                }
            }
        });
        pullToBothLayout.setRefreshListener(new BaseBothListener() {
            @Override
            public void refresh() {
                isRefresh = true;
                page = 1;
                getJob();
            }

            @Override
            public void loadMore() {
                isRefresh = false;
                page++;
                getJob();
            }
        });
    }

    //关闭下拉刷新
    private void closePullTo() {
        pullToBothLayout.finishRefresh();
        pullToBothLayout.finishLoadMore();
    }

    @Override
    public void setTitleBarColor() {

    }

    @Override
    protected boolean isStatusBarBlack() {
        return true;
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_part_search;
    }

    @Override
    public void initView() {
        ViewGroup.LayoutParams params = statusBarPlace.getLayoutParams();
        params.height = ScreenUtil.getStatusBarHeight(this);
        statusBarPlace.setLayoutParams(params);
        screenSexAdapter = new PartSearchAdapter(this, sexList);
        RecyclerView.ItemAnimator animator = recycle_1.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        GridLayoutManager layoutManager = new GridLayoutManager(this, 4);
        recycle_1.setHasFixedSize(true);
        recycle_1.setLayoutManager(layoutManager);
        GridItemDecoration divider = new GridItemDecoration.Builder(Objects.requireNonNull(this))
                .setHorizontalSpan(R.dimen.dp9)
                .setVerticalSpan(R.dimen.dp9)
                .setColorResource(R.color.whiteffffff)
                .setShowLastLine(false)
                .build();
        recycle_1.addItemDecoration(divider);
        recycle_1.setAdapter(screenSexAdapter);


        LinearLayoutManager manager = new LinearLayoutManager(this);
        if (dailyAdapter == null) {
            dailyAdapter = new PartApplyAdapter(this, list);
        }
        recycle_2.setHasFixedSize(true);
        recycle_2.setNestedScrollingEnabled(false);
        // 第一种，直接取消动画
        RecyclerView.ItemAnimator animator1 = recycle_2.getItemAnimator();
        if (animator1 instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator1).setSupportsChangeAnimations(false);
        }
        recycle_2.setLayoutManager(manager);
        recycle_2.setAdapter(dailyAdapter);
        dailyAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //跳转兼职详情
                startActivity(new Intent(PartSearchActivity.this, PartDetailActivity.class).putExtra("jobId", list.get(position).getJobId()));
            }
        });
        screenSexAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //点击热搜
                search = sexList.get(position).getDetail();
                edit_search.setText(search);
                isRefresh = true;
                page = 1;
                getJob();
            }
        });
        edit_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String input = edit_search.getText().toString();
                    if (!"".equals(input)) {
                        isRefresh = true;
                        page = 1;
                        getJob();
                    } else {
                        NewsToastUtils.showToast(App.getContext(), "请输入搜索内容！");
                    }
                    return true;
                }
                return false;
            }
        });

    }

    @OnClick({R.id.iv_close})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.iv_close: //关闭页面
                finish();
                break;

        }
    }

    //有数据
    private void haveData() {
        pullToBothLayout.setVisibility(View.VISIBLE);
        ll_rm.setVisibility(View.GONE);
        search_noData.setVisibility(View.GONE);
    }

    //无数据
    private void noData() {
        pullToBothLayout.setVisibility(View.GONE);
        ll_rm.setVisibility(View.GONE);
        search_noData.setVisibility(View.VISIBLE);

    }


    @Override
    public void initData() {
        getKeyWord();
    }

    //获取热门按键
    private void getKeyWord() {
        NoValidationTask.getApiService().getKeyWord().enqueue(new MyCallback<PartBaseEntity>(PartSearchActivity.this) {
            @Override
            protected void onSuccess(Response<PartBaseEntity> response) {
                assert response.body() != null;
                String jsonStr = JSONObject.toJSONString(response.body().getData());
                JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                for (int i = 0; i < jsonArray.size(); i++) {
                    ScreenEntity screenEntity = new ScreenEntity();
                    screenEntity.setDetail(jsonArray.getString(i));
                    sexList.add(screenEntity);
                }
                screenSexAdapter.notifyDataSetChanged();
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //获取数据
    private void getJob() {
        NoValidationTask.getApiService().getHomeJobs(page, null, null, null, search).enqueue(new MyCallback<PartBaseEntity>(PartSearchActivity.this) {
            @Override
            protected void onSuccess(Response<PartBaseEntity> response) {
                assert response.body() != null;
                String jsonStr = JSONObject.toJSONString(response.body().getData());
                JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                if (isRefresh) {
                    list.clear();
                    if (jsonArray.size() > 0) {
                        haveData();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            DailyEntity dailyEntity = new DailyEntity();
                            dailyEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                            dailyEntity.setJobId(jsonArray.getJSONObject(i).getInteger("id") + "");
                            dailyEntity.setLabel(jsonArray.getJSONObject(i).getString("jobPayType"));
                            dailyEntity.setMoney(jsonArray.getJSONObject(i).getInteger("jobPay") + "");
                            dailyEntity.setUnit(jsonArray.getJSONObject(i).getString("jobPayUnit"));
                            dailyEntity.setGsName(jsonArray.getJSONObject(i).getString("jobCompany"));
                            dailyEntity.setLocation(jsonArray.getJSONObject(i).getString("jobAddress"));
                            list.add(dailyEntity);
                        }

                    } else {
                        noData();
                    }
                } else {
                    if (jsonArray.size() > 0) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            DailyEntity dailyEntity = new DailyEntity();
                            dailyEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                            dailyEntity.setJobId(jsonArray.getJSONObject(i).getInteger("id") + "");
                            dailyEntity.setLabel(jsonArray.getJSONObject(i).getString("jobPayType"));
                            dailyEntity.setMoney(jsonArray.getJSONObject(i).getInteger("jobPay") + "");
                            dailyEntity.setUnit(jsonArray.getJSONObject(i).getString("jobPayUnit"));
                            dailyEntity.setGsName(jsonArray.getJSONObject(i).getString("jobCompany"));
                            dailyEntity.setLocation(jsonArray.getJSONObject(i).getString("jobAddress"));
                            list.add(dailyEntity);
                        }
                    }
                }
                dailyAdapter.notifyDataSetChanged();
                closePullTo();
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }
}
